<?php

  class UtilModel extends Model{

    /**
        * API统一签名函数
        *
        * @param array $params 不包括sn
        * @return string
        */
      public function api_signature($params, $secret) {
      ksort($params);
      $tmp = array();
      foreach ($params as $key => $val) {
        $tmp[] = $key . $val;
      }
      $tmp = implode('', $tmp);
      return md5($tmp . $secret);        
    }

      /**
       * 组装url及参数
       *
       * @param string $url
       * @param array $params
       * @param boolean $encodeAmp 是否使用&amp;
       * @return string
       */
      public function pack_url_params($url, $params, $encodeAmp = false) {
        $glue = $encodeAmp ? '&amp;' : '&';
        $params = (array) $params;
      
        if ($url != '' && $params) {
          if (strrpos($url, '?') === false) {
            $url .= '?';
              } elseif (substr($url, -1) != '?' && substr($url, -1) != '&' && substr($url, -4) != '&amp;') {
            $url .= $glue;
          }
        }
      
        $tmp = array();
        foreach ($params as $key => $one) {
          $tmp[] = rawurlencode($key) . "=" . rawurlencode($one);
        }
        $tmp = implode($glue, $tmp);
      
        return $url . $tmp;
      }

    /**
        * 组装并签名
        *
        * @param string $url API不包括?和任何参数
        * @param array $params 除固定参数外的所有参数
        * @param array $postParams post提交的参数加入签名，不加如url
        * @return string
        */
       public function pack_passport_api($url, $params, $secretKey,$postParams = array()) {
          $config=array('PASSPORT_WHITELIST_IP'=>'127.0.0.1');
          $params['t'] = time();
          empty($params['ip']) && $params['ip'] = $config['PASSPORT_WHITELIST_IP'];
          $params['sn'] = $this->api_signature(array_merge($params, $postParams),$secretKey);
          return $this->pack_url_params($url, $params);
       }

      public function getParams($mainParams){
          $result=array();
          $arr=explode("&",$mainParams);
          foreach ($arr as $mainParam) {
            $mainKeyValue=explode("=", $mainParam);
            $result[$mainKeyValue[0]]=$mainKeyValue[1];
          }
          return $result;
      }

  }